package blogger.servlets;

import java.io.IOException;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import blogger.model.entity.UserEntity;
import blogger.model.utils.EMF;


public class LoginServlet extends HttpServlet{
	protected void doGet(HttpServletRequest httpServletRequest,
			HttpServletResponse httpServletResponse) throws ServletException,
			IOException {
		String login = httpServletRequest.getParameter("login");
		String pass = httpServletRequest.getParameter("pass");
		EntityManager entityManager = EMF.get().createEntityManager();
		try {
			Query query = entityManager.createQuery("select u from UserEntity u where u.login = :login and u.pass = :pass");
			query.setParameter("login", login);
			query.setParameter("pass", pass);
			UserEntity user = null;
			try {
				user = (UserEntity) query.getSingleResult();
			} catch (NoResultException e) {
				user = null;
			}

			if (user != null) {
				httpServletRequest.getSession(true).setAttribute("id",user.getId());
				httpServletResponse.sendRedirect("Blogger.html");
			} else {
				httpServletResponse.sendRedirect("index.html");
			}
		} finally {
			entityManager.close();
		}
	}
}
